package com.jy.adscm.zltx.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.zltx.bean.SjAttachment;
import com.jy.adscm.zltx.mapper.mysql.SjAttachmentMapper;
import com.jy.adscm.zltx.service.SjAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2018-11-08
 */
@Service
public class SjAttachmentServiceImpl extends ServiceImpl<SjAttachmentMapper, SjAttachment> implements SjAttachmentService {
     @Autowired
    JyUserMapper jyUserMapper;
    @Override
    public List<SjAttachment> selectSjAttachments(Integer fileId) throws AdscmSystemException {
        Wrapper<SjAttachment> wrapper =new EntityWrapper<>();
        wrapper.eq("fileId",fileId);
        List<SjAttachment> sjAttachments = super.selectList(wrapper);
        for (SjAttachment sjAttachment : sjAttachments) {
            if (sjAttachment.getUploadPerson()!=null&&!"".equals(sjAttachment.getUploadPerson())){
                JyUser jyUser = jyUserMapper.selectById(sjAttachment.getUploadPerson());
                sjAttachment.setUploadPersonName(jyUser.getName());
            }
        }
        return sjAttachments;
    }

    @Override
    public Boolean deleteSjAttachments(Integer fileId, Token token) throws AdscmSystemException {
        boolean delete= false;
        SjAttachment sjAttachment = super.selectById(fileId);
        if (AdscmBaseUtils.getInstance().isNotEmpty(sjAttachment.getUploadPerson(),null)){
            if (sjAttachment.getUploadPerson().equals(token.getUser().getId().toString())){
                File file=new File(sjAttachment.getFilePath());
                if (file.exists()){
                    file.delete();
                }
                delete  = super.deleteById(fileId);
            }else {
                throw  new  AdscmSystemException("您不能删除！");
            }
        }
        return delete;
    }


}
